package com.ly.nio;
import	java.nio.channels.SelectionKey;
import	java.nio.channels.Selector;

import java.nio.channels.*;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import	java.util.Scanner;
import	java.nio.ByteBuffer;
import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * @Classname NioNonBlock
 * @Description TODO
 * @Date 2020/9/30 20:06
 * @Author 冷心影翼
 */
public class NioNonBlock {

	public static void main(String[] args) throws IOException {
//		server();
		client();
	}

	public static void client() throws IOException {
		SocketChannel channel = SocketChannel.open(new InetSocketAddress("127.0.0.1.txt",8848));

		ByteBuffer buffer = ByteBuffer.allocate(1024);
		//设置为非阻塞模式
		channel.configureBlocking(false);
		Scanner scanner = new Scanner(System.in);

		while (scanner.hasNextLine()) {
			buffer.put(scanner.next().getBytes());
			buffer.flip();
			channel.write(buffer);

			buffer.clear();
		}

		channel.close();
	}

	public static void server() throws IOException {
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		//设置非阻塞
		serverSocketChannel.configureBlocking(false);
		serverSocketChannel.bind(new InetSocketAddress(8848));

		//获取选择器
		Selector selector = Selector.open();
		//注册选择器，selectionkey为  OP_ACCEPT 接收状态
		//selectionkey  可以为  OP_READ  读状态  OP_CONNECT 连接状态  OP_ACCEPT 接收状态  OP_WRITE 写状态
		serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);

		while (selector.select()>0) {
			Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
			//选择器迭代
			while (iterator.hasNext()) {
				SelectionKey key = iterator.next();
				//准备状态
				if(key.isAcceptable()) {
					SocketChannel socketChannel = serverSocketChannel.accept();
					socketChannel.configureBlocking(false);
					//通道注册选择器
					socketChannel.register(selector,SelectionKey.OP_READ);
				}else if(key.isReadable()) {
					SocketChannel channel = (SocketChannel) key.channel();
					ByteBuffer buffer = ByteBuffer.allocate(1024);
					int len = 0;

					while ((len = channel.read(buffer)) > 0) {
						buffer.flip();
						System.out.println(new String(buffer.array(),0,len));
						buffer.clear();
					}
				}
			}
			//清除选择键
			iterator.remove();
		}
	}
}
